package com.pfm.graficos;

import min3d.core.Object3dContainer;
import min3d.core.RendererActivity;
import min3d.parser.IParser;
import min3d.parser.Parser;
import min3d.vos.Light;
import min3d.vos.Number3d;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;

public class LoadLibro extends RendererActivity  implements SensorEventListener {
	private Object3dContainer objModel;
	private final float FILTERING_FACTOR = .3f;
	
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private Number3d mAccVals;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mAccVals = new Number3d();
	}
	
	@Override
	public void initScene() {
		
			scene.lights().add(new Light());
		
			IParser parser = Parser.createParser(Parser.Type.OBJ,
					getResources(), "com.pfm.cuento:raw/libro_obj", true);
			parser.parse();
	
			objModel = parser.getParsedObject();
			objModel.scale().x = objModel.scale().y = objModel.scale().z = 2.7f;
			scene.addChild(objModel);
			
			mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
	}
	
	@Override
	public void updateScene() {
		objModel.rotation().x++;
		objModel.rotation().y++;
	}
	
	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// TODO Auto-generated method stub
	}
	
	@Override
	public void onSensorChanged(SensorEvent event) {
		if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
            return;
		
		mAccVals.x = (float) (-event.values[1] * FILTERING_FACTOR + mAccVals.x * (1.0 - FILTERING_FACTOR));
		mAccVals.y = (float) (event.values[0] * FILTERING_FACTOR + mAccVals.y * (1.0 - FILTERING_FACTOR));
		
		scene.camera().position.x = mAccVals.x * .2f;
        scene.camera().position.y = mAccVals.y * .2f;
        
        scene.camera().target.x = -scene.camera().position.x;
        scene.camera().target.y = -scene.camera().position.y;
	}
//	
//    @Override public boolean onTouchEvent(MotionEvent e) {
//        float x = e.getX();
//        float y = e.getY();
//        switch (e.getAction()) {
//        case MotionEvent.ACTION_MOVE:
//            float dx = x - mPreviousX;
//            float dy = y - mPreviousY;
//            scene.camera().target.x += dx * TOUCH_SCALE_FACTOR;
//            scene.camera().target.y += dy * TOUCH_SCALE_FACTOR;
//        }
//        mPreviousX = x;
//        mPreviousY = y;
//        return true;
//    }
//	
//	private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
//    private float mPreviousX;
//    private float mPreviousY;
}